<template>
  <div class="import-upload">
    <el-upload
      ref="uploadRef"
      :action="uploadUrl"
      :headers="headers"
      :before-upload="handleBeforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :show-file-list="false"
      accept=".xlsx,.xls"
    >
      <el-button type="primary" :loading="loading">
        <el-icon><Upload /></el-icon>
        {{ loading ? '导入中...' : '导入' }}
      </el-button>
    </el-upload>

    <el-button
      v-if="props.showTemplate"
      type="primary"
      link
      @click="handleDownloadTemplate"
      style="margin-left: 10px"
    >
      下载模板
    </el-button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import http from '@/util/http1'

const props = defineProps({
  uploadUrl: {
    type: String,
    required: true,
  },
  templateUrl: {
    type: String,
    required: true,
  },
  fileSize: {
    type: Number,
    default: 10, // 默认10MB
  },
  showTemplate: {
    type: Boolean,
    default: false, // 默认不显示下载模板按钮
  },
})

const emit = defineEmits(['success'])

const uploadRef = ref()
const loading = ref(false)

// 上传前的验证
const handleBeforeUpload = (file) => {
  loading.value = true

  // 验证文件类型
  const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase())
  if (!isExcel) {
    ElMessage.error('请上传Excel文件')
    loading.value = false
    return false
  }

  // 验证文件大小
  const isLt10M = file.size / 1024 / 1024 < props.fileSize
  if (!isLt10M) {
    ElMessage.error(`文件大小不能超过 ${props.fileSize}MB!`)
    loading.value = false
    return false
  }

  return true
}

// 上传成功
const handleSuccess = (response) => {
  loading.value = false
  if (response.flag) {
    ElMessage.success('导入成功')
    emit('success')
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
}

// 上传失败
const handleError = () => {
  loading.value = false
  ElMessage.error('导入失败')
}

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    const res = await http.get(props.templateUrl, {
      responseType: 'blob',
    })

    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const downloadElement = document.createElement('a')
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = '导入模板.xlsx'

    document.body.appendChild(downloadElement)
    downloadElement.click()
    document.body.removeChild(downloadElement)
    window.URL.revokeObjectURL(href)

    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('模板下载失败:', error)
    ElMessage.error('模板下载失败')
  }
}
</script>

<style lang="less" scoped>
.import-upload {
  display: inline-block;
}
</style>
